import React, { useState, useEffect } from "react";
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Radio,
  Checkbox,
  Upload,
  message,
  Cascader,
  Modal
} from "antd";
import { CityOption } from '../../utils/china' //城市数据
import Cookies from "js-cookie";

import { apiEditHouse } from '../../api'

import { useLocation, useNavigate } from 'react-router-dom'
import { usePlugins, Amap, Marker as AmapMarker, } from "@amap/amap-react";

const { Option } = Select;
const { TextArea } = Input;

const Index = () => {

  const navigate = useNavigate()
  const location = useLocation()//获取路由信息
  const { state }: any = location; // 解构 state

  const [NameValue, setNameValue] = useState('')//楼盘名称受控

  useEffect(() => {

    if (state !== null) {
      form.setFieldsValue({
        area: state.area,//所属地区
        name: state.name,//名称
        price: state.price,//价格
        rent: state.rent,//租金
        address: state.address,//地址
        data: state.time,//时间
        cell: state.cell,//电话
        booking: state.booking,//预售证书
        developers: state.developers,//开发商
        coordinates: state.coordinates,//地图坐标
        envelopes: state.envelopes,//购房红包
        discounts: state.discounts,//优惠楼盘
        situation: state.situation,//装修情况
        salesStatus: state.salesStatus,//销售状态
        types: state.types,//楼盘类型
        tags: state.tags,//特色标签
        featured: state.featured,//推荐位
        // 缩略图
        // 看房视频
        // 全景看房
        introduction: state.introduction,//楼盘介绍
        buildingtypes: state.buildingtypes,//建筑类型
        property: state.property,//产权年限	
        propertys: state.propertys,// 占地面积
        structure: state.structure,//建筑面积
        ratio: state.ratio,//容积率
        greening: state.greening,//绿化率	
        number: state.number,//规划户数
        situations: state.situations,//车位情况
        spaceType: state.spaceType,//物业类型	
        company: state.company,//物业公司
        propertyfee: state.propertyfee//物业费
      });
      setCenter(state.coordinates.split(','))
      console.log(state.coordinates);

    } else {
      setCenter([116.473571, 39.993083])

    }
  }, []);

  // +++++++++++++++++++
  const onFinish = (values: any) => {
    console.log(values);
    state
      ? apiEditHouse({ values, id: state.id, state: state.state, cell: state.cell, broker: state.broker, img, video, coordinates: center }).then(res => {
        message.success(res.data.msg)
        if (res.data.code === 1) {
          navigate(-1)
        }
      })
      : apiEditHouse({ values, img, video, coordinates: center }).then(res => {
        message.success(res.data.msg)
        if (res.data.code === 1) {
          navigate(-1)
        }
      })
  };

  const [form] = Form.useForm();


  //装修情况
  const option = [
    {
      label: "毛胚",
      value: "毛胚",
    },
    {
      label: "简装",
      value: "简装",
    },
    {
      label: "精装",
      value: "精装",
    },
    {
      label: "豪装",
      value: "豪装",
    },
  ];

  //销售状态
  const options = [
    {
      label: "在售",
      value: "在售",
    },
    {
      label: "新盘",
      value: "新盘",
    },
    {
      label: "尾盘",
      value: "尾盘",
    },
    {
      label: "售罄",
      value: "售罄",
    },
    {
      label: "未开盘",
      value: "未开盘",
    },
  ];

  //楼盘类型
  const typeOption = [
    { label: "住宅", value: "住宅" },
    { label: "别墅", value: "别墅" },
    { label: "商铺", value: "商铺" },
    { label: "写字楼", value: "写字楼" },
    { label: "公寓", value: "公寓" },
    { label: "底商", value: "底商" },
  ];

  //特色标签
  const tagOption = [
    { label: "小户型", value: "小户型" },
    { label: "低密居所", value: "低密居所" },
    { label: "旅游地产", value: "旅游地产" },
    { label: "教育地产", value: "教育地产" },
    { label: "宜居生态", value: "宜居生态" },
    { label: "海景楼盘", value: "海景楼盘" },
  ];

  //推荐位
  const recommendOption = [
    { label: "首页热搜楼盘", value: "首页热搜楼盘" },
    { label: "首页热搜推荐", value: "首页热搜推荐" },
    { label: "首页刚需推荐", value: "首页刚需推荐" },
    { label: "首页列表推荐", value: "首页列表推荐" },
  ];


  //级联选择
  const [ThreeValue, setThreeValue] = useState<any>({})
  const onChanges = (value: any) => {

    let list: any = {}
    // 转换对象格式
    for (var key in value) {
      list[key] = value[key];
    }

    setThreeValue(list);
  }

  // 图片上传
  const [img, setImg] = useState('');
  const handleChange = (res: any) => {
    console.log(res, 'resres');

    if (res.file.response) {
      setImg(res.file.response.data.url)
    }
  }

  // 视频上传
  const [video, setVideo] = useState('');
  const handleChangeVideo = (res: any) => {
    console.log(res, 'video');

    if (res.file.response) {
      setVideo(res.file.response.data.url)
    }
  }

  // 地图盒子
  const [mapDiv, setMapDiv] = useState(false);

  const handleCancel = () => {
    setMapDiv(false)
  }
  // 存储地图坐标
  const [center, setCenter]: any = useState([])

  const [addressList, setAddressList] = useState([])

  const [opt, setOpt] = useState([])

  const [addressName, setAddressName] = useState('')

  // 开启搜索插件
  const AMap: any = usePlugins(['AMap.AutoComplete'])

  //搜索地址
  const searchAddress = (e: any) => {
    // 调用搜索组件实例
    const searchMap = new AMap.AutoComplete()

    //搜索
    searchMap.search(e, (st: any, res: any) => {
      
      setAddressList(res.tips)
      //容错处理
      res.tips && setOpt(res.tips.map((item: any) => {
        return <Option key={item.name + item.id}>{item.name}</Option>
      }))
    })
  }
  // 选择下拉框的时候  触发的回调
  const getAddress = (st: any, ops: any) => {
    addressList.forEach((item: any) => {
      if (st === item.name + item.id) {
        setAddressName(item.name + item.id)
        setCenter([item.location.lng, item.location.lat])
      }
    })
  }


  const btn = () => {
    setCenter(center)
    setMapDiv(false)
  }

  return (
    <div>
      <Card>
        <Form
          form={form}
          style={{ display: "flex", flexDirection: "column" }}
          onFinish={onFinish}

        >

          {/* 三级联动 */}
          <Form.Item
            label="所属地区"
            rules={[{ required: true, message: "所属地区不能为空" }]}
            name="area"
            style={{ width: "50%" }}
          >
            <Cascader options={CityOption} onChange={onChanges} placeholder="请选择城市数据" fieldNames={{ label: 'name', value: 'name', children: 'children' }} />
          </Form.Item>

          <div style={{ display: "flex" }}>
            <Form.Item
              label="楼盘名称"
              rules={[{ required: true, message: "楼盘名称不能为空" }]}
              name="name"
              style={{ width: "40%" }}
            >
              <Input value={NameValue} onChange={(e) => { setNameValue(e.target.value) }} placeholder="请输入楼盘名称" style={{ width: "300px" }} />
            </Form.Item>

            <div style={{ display: "flex", width: "60%" }}>
              <Form.Item label="均价" name="price" rules={[{ required: true, message: "均价不能为空" }]}>
                <Input style={{ width: "200px", marginRight: "20px" }} />
              </Form.Item>
              <Form.Item label="租金" name="rent" rules={[{ required: true, message: "租金不能为空" }]}>
                <Input style={{ width: "200px", marginRight: "20px" }} />
              </Form.Item>
              <Form.Item>
                <Select defaultValue={["元/m2"]}>
                  <Option value="元/m2">元/m2</Option>
                  <Option value="元/套">元/套</Option>
                </Select>
              </Form.Item>
            </div>
          </div>
          <div style={{ display: "flex" }}>
            <Form.Item
              label="楼盘地址"
              rules={[{ required: true, message: "楼盘地址不能为空" }]}
              name="address"
              style={{ width: "50%" }}
            >
              <Input placeholder="请输入楼盘地址" style={{ width: "300px" }} />
            </Form.Item>

            <Form.Item
              rules={[{ required: true, message: "售楼处地址不能为空" }]}
              label="售楼处地址" style={{ width: "50%" }} name="address" >
              <Input
                placeholder="请输入售楼处地址"
                style={{ width: "300px" }}
              />
            </Form.Item>
          </div>
          {
            state !== null
              ? <div style={{ display: "flex" }}>
                <Form.Item label="开盘时间" style={{ width: "50%" }} name="data"
                  rules={[{ required: true, message: "开盘时间不能为空" }]}>
                  <Input type="data" style={{ width: "300px" }} />
                </Form.Item>
                <Form.Item label="交房时间" style={{ width: "50%" }} name="data"
                  rules={[{ required: true, message: "交房不能为空" }]}>
                  <Input type="data" style={{ width: "300px" }} />
                </Form.Item>
              </div>
              : <div style={{ display: "flex" }}>
                <Form.Item label="开盘时间" style={{ width: "50%" }}
                  rules={[{ required: true, message: "开盘时间不能为空" }]}>
                  <Input type="date" style={{ width: "300px" }} />
                </Form.Item>
                <Form.Item label="交房时间" style={{ width: "50%" }}
                  rules={[{ required: true, message: "交房时间不能为空" }]}>
                  <Input type="date" style={{ width: "300px" }} />
                </Form.Item>
              </div>
          }
          <div style={{ display: "flex" }}>
            <Form.Item label="售楼电话" style={{ width: "50%" }} name="cell"
              rules={[{ required: true, message: "售楼电话不能为空" }]}>
              <Input style={{ width: "300px" }} />
            </Form.Item>
            <Form.Item label="预售证号" style={{ width: "50%" }} name='booking'
              rules={[{ required: true, message: "预售证号不能为空" }]}>
              <Input style={{ width: "300px" }} />
            </Form.Item>
          </div>
          <div style={{ display: "flex" }}>
            <Form.Item label="开发商" style={{ width: "50%" }} name='developers'
              rules={[{ required: true, message: "开发商不能为空" }]}>
              <Input style={{ width: "300px" }} />
            </Form.Item>


            <div style={{ width: "50%", display: 'flex' }} >
              <Form.Item label="地图坐标" style={{ width: "30%", marginRight: "100px" }} name='coordinates'>
                <Input style={{ width: "200px" }} />
              </Form.Item>
              <Button onClick={() => { setMapDiv(true) }}>标注位置</Button>

              <Modal visible={mapDiv} footer={null} onCancel={handleCancel} width={800} style={{ marginLeft: '23.5%' }}>
                {/* 下拉搜索框 */}
                <Select style={{ width: '80%', height: '42px', marginTop: '20px', marginRight: '15px' }}
                  showSearch // 允许select开启搜索功能
                  onSearch={searchAddress} //搜索方法
                  onSelect={getAddress} //获取地址
                >
                  {opt}
                </Select>

                <Button onClick={btn}>确认</Button>

                <div style={{ width: '100%', height: '400px' }}>
                  {/* 地图 */}
                  <Amap
                    zoom={15}
                    center={center}
                  >
                    <AmapMarker
                      position={center}
                      label={{
                        content: addressName,
                        direction: 'bottom',
                      }}
                    />
                  </Amap>
                </div>
              </Modal>
            </div>
          </div>

          <Form.Item label="购房红包" name='envelopes' rules={[{ required: true, message: "购房红包不能为空" }]}>
            <Input style={{ width: "300px" }} placeholder="请输入" />
          </Form.Item>

          <Form.Item label="优惠楼盘" name='discounts'>
            {
              state ? (state.discounts === '1' ? <Checkbox defaultChecked /> : <Checkbox />) : <Checkbox />
            }
          </Form.Item>
          <Form.Item label="装修情况" name='situation' rules={[{ required: true, message: "装修情况不能为空" }]}>
            <Radio.Group options={option} />
          </Form.Item>

          <Form.Item label="销售状态" name='salesStatus' rules={[{ required: true, message: "销售状态不能为空" }]}>
            <Radio.Group options={options} />
          </Form.Item>
          <Form.Item label="楼盘类型" name="types" rules={[{ required: true, message: "楼盘类型不能为空" }]}>
            <Checkbox.Group options={typeOption} />
          </Form.Item>
          <Form.Item label="特色标签" name='tags' rules={[{ required: true, message: "特色标签不能为空" }]}>
            <Checkbox.Group options={tagOption} />
          </Form.Item>

          {/*  */}
          <Form.Item label="推荐位" name='featured' rules={[{ required: true, message: "推荐位不能为空" }]}>
            <Checkbox.Group options={recommendOption} />
          </Form.Item>


          <Form.Item label="缩略图" rules={[{ required: true, message: "缩略图不能为空" }]}>
            {/* 图片上传 */}
            <>
              {
                state
                  ? <img style={{ width: '30%', height: '200px' }} src={img || state.img} />
                  : <img style={{ width: '30%', height: '200px' }} src={img} />
              }
            </>
            <Upload
              className="avatar-uploader"
              showUploadList={false}
              action="/api/getImg"
              onChange={handleChange}
              headers={{
                Authorization: Cookies.get('token') as string
              }}
            >
              {/* {img ? <img src={img} alt="avatar" style={{ width: '100%' }} /> : uploadButton} */}
              <Button>上传图片</Button>
            </Upload>
          </Form.Item>


          <Form.Item label="看房视频" rules={[{ required: true, message: "看房视频不能为空" }]}>
            <Upload
              className="avatar-uploader"
              showUploadList={false}
              action="/api/getVideo"
              onChange={handleChangeVideo}
              headers={{
                Authorization: Cookies.get('token') as string
              }}
            >
              <Button>上传视频</Button>
            </Upload>
          </Form.Item>

          <Form.Item label="全景看房">
            <Input placeholder="请输入楼盘坐标" style={{ width: "300px" }} />
          </Form.Item>
          {/*  */}


          <Form.Item label="楼盘介绍" name='introduction' rules={[{ required: true, message: "楼盘介绍不能为空" }]}>
            <TextArea
              style={{ width: "500px" }}
              autoSize={{ minRows: 10, maxRows: 30 }}
            />
          </Form.Item>
          <div style={{ display: "flex" }}>
            <Form.Item label="建筑类型" name='buildingtypes' rules={[{ required: true, message: "建筑类型不能为空" }]}>
              <Input style={{ width: "300px", marginRight: "20px" }} />
            </Form.Item>
            <Form.Item label="产权年限" name='property' rules={[{ required: true, message: "产权年限不能为空" }]}>
              <Input style={{ width: "300px" }} />
            </Form.Item>
          </div>
          <div style={{ display: "flex" }}>
            <Form.Item label="占地面积" name='propertys' rules={[{ required: true, message: "占地面积不能为空" }]}>
              <Input style={{ width: "300px", marginRight: "20px" }} />
            </Form.Item>
            <Form.Item label="建筑面积" name='structure' rules={[{ required: true, message: "建筑面积不能为空" }]}>
              <Input style={{ width: "300px" }} />
            </Form.Item>
          </div>

          <div style={{ display: "flex" }}>
            <Form.Item label="容积率" name='ratio' rules={[{ required: true, message: "容积率不能为空" }]}>
              <Input style={{ width: "300px", marginRight: "20px" }} />
            </Form.Item>
            <Form.Item label="绿化率" name='greening' rules={[{ required: true, message: "绿化率不能为空" }]}>
              <Input style={{ width: "300px" }} />
            </Form.Item>
          </div>
          <div style={{ display: "flex" }}>
            <Form.Item label="规划户数" name='number' rules={[{ required: true, message: "规划户数不能为空" }]}>
              <Input style={{ width: "300px", marginRight: "20px" }} />
            </Form.Item>
            <Form.Item label="车位情况" name='situations' rules={[{ required: true, message: "车位情况不能为空" }]}>
              <Input style={{ width: "300px" }} />
            </Form.Item>
          </div>
          <div style={{ display: "flex" }}>
            <Form.Item label="物业类型" name='spaceType' rules={[{ required: true, message: "物业类型不能为空" }]}>
              <Input style={{ width: "300px", marginRight: "20px" }} />
            </Form.Item>
            <Form.Item label="物业公司" name='company' rules={[{ required: true, message: "物业公司不能为空" }]}>
              <Input style={{ width: "300px" }} />
            </Form.Item>
          </div>
          <Form.Item label="物业费" name='propertyfee' rules={[{ required: true, message: "物业费不能为空" }]}>
            <Input style={{ width: "300px" }} />
          </Form.Item>


          <Form.Item style={{ textAlign: "center" }}>
            {state === null ? (
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            ) : (
              <Button type="primary" htmlType="submit">
                更新
              </Button>
            )}
          </Form.Item>
        </Form>
      </Card>
    </div >
  );
}

export default Index